package db_live

import (
	"errors"
	"fmt"

	"longmen/server/config/global"
	"longmen/server/internal/services/nami/utils"
	_const "longmen/server/pkg/common/helper/const"
	"longmen/server/pkg/common/helper/timehelper"
	"longmen/server/pkg/db/mysql"
	"longmen/server/pkg/db/mysql/db_main"
	"longmen/server/pkg/db/mysql/models/models_live"
	db_main3 "longmen/server/pkg/db/mysql/models/models_main"
	"longmen/server/pkg/protobuf"
	"time"

	"longmen/server/pkg/common/api_models"

	"gorm.io/gorm"
)

func GetLiveParam(param map[string]interface{}) (*models_live.Live, error) {
	o := &models_live.Live{}
	err := mysql.Condition(global.Live().Model(&models_live.Live{}), param, "", "", 0, 0).Find(o).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		err = nil
	}
	if err != nil {
		return nil, err
	}
	return o, err
}

func GetLivePbParam(param map[string]interface{}, order string, page, size int) ([]*protobuf.LiveInfo, error) {
	var (
		err     error
		dbQuery = make([]*models_live.Live, 0)
		result  = make([]*protobuf.LiveInfo, 0)
		//liveInfoPool = sync.Pool{
		//	New: func() interface{} {
		//		return &pt.LiveInfo{}
		//	},
		//}
	)

	table := global.Live().Model(&models_live.Live{})
	mysql.Condition(table, param, "", order, page, size)

	if err = table.Find(&dbQuery).Error; errors.Is(err, gorm.ErrRecordNotFound) {
		err = nil
	}
	if err != nil {
		return nil, err
	}

	for _, live := range dbQuery {
		//des := liveInfoPool.Get().(*pt.LiveInfo)
		//copier.Copy(&des, &models_live)
		//result = append(result, des)
		//liveInfoPool.Put(des)
		result = append(result, &protobuf.LiveInfo{
			Title:        live.Title,
			Thumb:        live.Thumb,
			PullUrl:      live.PullUrl,
			Categoryid:   uint32(live.Categoryid),
			AnchorAvatar: live.AnchorAvatar,
			AnchorName:   live.AnchorName,
			Category:     uint32(live.Category),
			Hot:          uint32(live.Hot),
			Anchorid:     uint32(live.Anchorid),
			Matchid:      uint32(live.Matchid),
			Tag:          live.Tag,
			TagTitle:     "",
			TagColor:     "",
			TagPoint:     0,
			TagType:      0,
		})
	}

	return result, err
}

func GetLivePbParamForIds(ids []int) ([]*protobuf.LiveInfo, error) {
	o := make([]*protobuf.LiveInfo, 0)
	err := global.Live().Model(&models_live.Live{}).Select("`title`,`thumb`,`pull_url`,`categoryid`,`anchor_avatar`,`anchor_name`,`category`,`hot`,`anchorid`,`matchid`,`tag`").Where("matchid", ids).Find(&o).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		err = nil
	}
	return o, err
}
func GetHotAnchor(ids []int) (int, error) {
	db := global.Live().Model(&models_live.Live{})
	var anchorid int
	err := db.Where("anchorid in ?", ids).Order("hot DESC").Limit(1).Pluck("anchorid", &anchorid).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		err = nil
	}
	return anchorid, err
}

func GetLivesParam(param map[string]interface{}, order string, page, size int) ([]*models_live.Live, error) {
	o := make([]*models_live.Live, 0)
	table := global.Live().Model(&models_live.Live{})
	mysql.Condition(table, param, "", order, page, size)
	err := table.Find(&o).Error
	return o, err
}

/**
 * @Author admin
 * @Description //TODO
 * @Date 15:18 2022/11/10
 * @Param
 * @return
 **/
func GetLivesAll() ([]*models_live.Live, error) {
	o := make([]*models_live.Live, 0)
	if err := global.Live().Model(&models_live.Live{}).Find(&o).Error; err != nil {
		return nil, err
	} else {
		return o, err
	}
}

func GetMatchLivesParam(MatchId, userid int, clieintIP string, page, size int) ([]*protobuf.Live, error) {
	o := make([]*models_live.Live, 0)
	err := global.Live().Find(&o).Where("matchid=?", MatchId).Order("hot desc").Limit(size).Offset((page - 1) * size).
		Find(&o).
		Error
	if err != nil {
		return nil, err
	}

	lives := make([]*protobuf.Live, 0)
	userArea, _ := mysql.GetIpToArea(clieintIP)

	for _, v := range o {
		// 检查屏蔽库是否返回动画直播
		v = Blocked(userArea, v)
		global.Log.Debugf("直播中的主播id:%v", v.Anchorid)
		lives = append(lives, &protobuf.Live{
			Anchorid:     uint32(v.Anchorid),
			AnchorName:   v.AnchorName,
			Title:        v.Title,
			Thumb:        v.Thumb,
			PullUrl:      v.PullUrl,
			ThumbY:       v.ThumbY,
			AnchorAvatar: v.AnchorAvatar,
			CategoryId:   int32(v.Categoryid),
			MatchId:      int64(v.Matchid),
			Isattent:     v.Isattent,
		})
	}
	return lives, err
}

func GetHotLive() ([]*models_live.Live, error) {
	o := make([]*models_live.Live, 0)
	err := global.Live().Raw("SELECT l.*  FROM db_user_rec ur LEFT JOIN models_live l ON l.anchorid=ur.uid WHERE l.status = 1 ORDER BY l.hot DESC").
		Find(&o).
		Error
	return o, err
}

func GetNewLivesParam(param map[string]interface{}, order string, page, size int) ([]*models_live.LiveBaseData, error) {
	o := make([]*models_live.LiveBaseData, 0)
	table := global.Live().Model(&models_live.Live{})
	mysql.Condition(table, param, "", order, page, size)
	err := table.Find(&o).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		err = nil
	}
	//for i := range o {
	//    util.ReplacePullUrl(o[i])
	//}
	return o, err
}

func InsertLive(session *gorm.DB, live *models_live.Live) error {
	if session == nil {
		session = global.Live()
	}
	err := session.Create(live).Error
	if err != nil {
		session.Rollback()
		return err
	}
	return nil
}

func UpdateLiveByTransactions(session *gorm.DB, columns []string, live *models_live.Live) error {
	if session == nil {
		session = global.Live()
	}
	err := session.Where("liveid = ?", live.Liveid).Select(columns).Updates(live).Error
	if err != nil {
		session.Rollback()
		return err
	}
	return nil
}

func UpdateLiveStatus(session *gorm.DB, liveId int64, status int) error {
	if session == nil {
		session = global.Live()
	}
	err := session.Model(&models_live.Live{}).Where("liveid = ?", liveId).Update("status", status).Error
	global.Log.Debugf("UpdateLiveStatus :%v", err)
	if err != nil {
		session.Rollback()
		return err
	}
	return nil
}

func DeleteLiveByTransactions(session *gorm.DB, live *models_live.Live) error {
	err := session.Where("anchorid = ? AND liveid = ?", live.Anchorid, live.Liveid).Delete(live).Error
	if err != nil {
		return err
	}
	return nil
}

func UpdateLivePlanStatus(session *gorm.DB, live *models_live.Live) error {
	if live.Matchid <= 0 { // 不是赛事直播直接跳过
		return nil
	}
	err := session.Model(&db_main3.AnchorLivePlan{}).Where("anchor_id = ? AND match_id = ?", live.Anchorid, live.Matchid).Update("status", _const.LIVE_PLAN_STATUS_FINISHED).Error
	if err != nil {
		return err
	}
	return nil
}

// 记录用户直播间访问历史
func LiveVisitRecord(live_id uint64, user_id uint64, platform uint32) (*protobuf.LiveVisitRecordResp, error) {
	// 直播间信息
	live := &models_live.Live{}
	err := global.Live().Where("liveid = ?", live_id).Order("id ASC").Limit(1).Find(&live).Error
	if err != nil {
		return &protobuf.LiveVisitRecordResp{
			Status: 2,
		}, err
	}

	var categoryTopKey = "LiveCategoryTop"
	var category models_live.LiveCategoryTop

	checkCategoryTop := global.GetRds().Exists(categoryTopKey).Val()
	if checkCategoryTop != 1 {
		err = global.Live().Model(&models_live.LiveCategoryTop{}).Where("id = ?", live.Category).Find(&category).Error
		if err != nil && err != gorm.ErrRecordNotFound {
			return &protobuf.LiveVisitRecordResp{
				Status: 2,
			}, err
		}
	}

	var categoryChildKey = "LiveCategoryChild"
	var childCategory models_live.LiveCategory
	checkCategoryChild := global.GetRds().Exists(categoryChildKey).Val()
	if checkCategoryChild != 1 {
		err = global.Live().Model(&models_live.LiveCategory{}).Where("id = ?", live.Categoryid).Find(&childCategory).Error
		if err != nil && err != gorm.ErrRecordNotFound {
			return &protobuf.LiveVisitRecordResp{
				Status: 2,
			}, err
		}
	}

	// 记录入库
	liveVisitRecord := &models_live.LiveStreamHistory{
		UserId:            int64(user_id),
		LiveStreamerId:    int64(live.Anchorid),
		LiveStreamId:      int64(live_id),
		Title:             live.Title,
		Thumb:             live.Thumb,
		CategoryID:        live.Category,
		CategoryName:      category.Title,
		ChildCategoryID:   live.Categoryid,
		ChildCategoryName: childCategory.Title,
		LastVisitTime:     time.Now().Unix(),
		AnchorName:        live.AnchorName,
		Platform:          platform,
	}

	if live.Anchorid == int(user_id) {
		return &protobuf.LiveVisitRecordResp{
			Status: 1,
		}, nil
	}

	var check int64
	err = global.Live().Model(&models_live.LiveStreamHistory{}).Where("user_id=? and anchorid=? and liveid=?", user_id, live.Anchorid, live.Liveid).Count(&check).Error

	if err != nil {
		return &protobuf.LiveVisitRecordResp{
			Status: 2,
		}, err
	}
	if check > 0 {
		//err = global.Live().Model(&liveVisitRecord).Where("user_id=? and anchorid=? and liveid=?", user_id, models_live.Anchorid, models_live.Liveid).Save(&liveVisitRecord).Error
		//if err != nil {
		//	return &pt.LiveVisitRecordResp{
		//		Status: 2,
		//	}, err
		//}

		return &protobuf.LiveVisitRecordResp{
			Status: 1,
		}, nil

	}

	err = global.Live().Create(&liveVisitRecord).Error
	if err != nil {
		return &protobuf.LiveVisitRecordResp{
			Status: 2,
		}, err
	}
	return &protobuf.LiveVisitRecordResp{
		Status: 1,
	}, nil
}

// 记录用户直播间访问历史
func LiveVisitList(user_id uint64, page int, size int, status int) (*protobuf.LiveVisitResp, error) {
	var (
		err, queryErr  error
		isFans, isLive int64
		total          int64
		//counts         int
		liveVisitList []*protobuf.LiveVisit
		queryLives    []*models_live.Live
		queryTags     []*db_main3.ConfigTag
		//
		getConfigTags = func() error {
			var (
				err2    error
				tagIDs  []int64
				liveIDs []uint64
			)

			for _, v := range liveVisitList {
				liveIDs = append(liveIDs, v.Liveid)
			}

			//if queryLives, counts = cache.GetInstance().QueryLiveByCatAndStatusArrays(liveIDs); counts == 0 {
			//	return err2
			//}
			/*if queryLives, err2 = GetLivesByLiveIDs(liveIDs); err != nil || len(queryLives) == 0 {
				return err2
			}*/

			for _, live := range queryLives {
				tagIDs = append(tagIDs, live.Tag)
			}

			if queryTags, err2 = mysql.GetConfigTagByIds2(tagIDs); err2 != nil {
				return err2
			}
			return nil
		}
		findTagInfo = func(liveid uint64) *db_main3.ConfigTag {
			if queryErr != nil {
				return nil
			}

			var tagID int64

			for _, live := range queryLives {
				if live.Liveid == int64(liveid) {
					tagID = live.Tag
					break
				}
			}

			if tagID == 0 {
				return nil
			}

			for _, tag := range queryTags {
				if int64(tag.Id) == tagID {
					tag.Operator = ""
					return tag
				}
			}

			return nil
		}
	)

	if status == 1 {
		if global.Live().Model(&models_live.LiveStreamHistory{}).
			Where("user_id=?", user_id).Count(&total).
			Order("last_visit_time desc").
			Offset((page-1)*size).Limit(size).
			Scan(&liveVisitList).Error != nil {
			return &protobuf.LiveVisitResp{
				LiveVisit: nil,
			}, nil
		}
	}

	if status == 2 {
		if global.Live().Model(&models_live.LiveStreamHistory{}).
			Joins("join db_live on db_live.anchorid=live_stream_visit_history.anchorid").
			Where("live_stream_visit_history.user_id=? and db_live.status=1", user_id).
			Count(&total).Select("live_stream_visit_history.*").
			Order("last_visit_time desc").
			Offset((page-1)*size).Limit(size).
			Scan(&liveVisitList).Error != nil {
			return &protobuf.LiveVisitResp{
				LiveVisit: nil,
			}, nil
		}
	}

	queryErr = getConfigTags()

	for idx, v := range liveVisitList {
		isFans = 0
		isLive = 0

		// TODO 优化...
		if err = global.Live().Model(&db_main3.AnchorFans{}).
			Where("fansid=? and anchorid=?", user_id, v.Anchorid).
			Count(&isFans).Error; err != nil {
			return &protobuf.LiveVisitResp{
				LiveVisit: liveVisitList,
			}, err
		}
		if isFans > 0 {
			liveVisitList[idx].IsFavorite = true
		}

		//TODO 优化...
		if err = global.Live().Model(&models_live.Live{}).
			Where("anchorid=? and status=1", v.Anchorid).
			Count(&isLive).Error; err != nil {
			return &protobuf.LiveVisitResp{
				LiveVisit: liveVisitList,
			}, err
		}
		if isLive > 0 {
			liveVisitList[idx].IsLive = true
		}

		if queryTag := findTagInfo(v.Liveid); queryTag != nil {
			liveVisitList[idx].TagId = int64(queryTag.Id)
			liveVisitList[idx].TagTitle = queryTag.Title
			liveVisitList[idx].TagColor = queryTag.Color
			liveVisitList[idx].TagPoint = int32(queryTag.Point)
			liveVisitList[idx].TagType = int32(queryTag.Type)
		}
	}

	return &protobuf.LiveVisitResp{
		Total:     total,
		LiveVisit: liveVisitList,
	}, nil
}

// 清除访问记录
func LiveVisitClean(user_id uint64) (*protobuf.LiveVisitRecordResp, error) {
	err := global.Live().Model(&models_live.LiveStreamHistory{}).Where("user_id=?", user_id).Delete(&models_live.LiveStreamHistory{}).Error
	if err != nil {
		return &protobuf.LiveVisitRecordResp{
			Status: 2,
		}, err
	}
	return &protobuf.LiveVisitRecordResp{
		Status: 1,
	}, err
}

// 用户背包
func UserBackpack(user_id int64) (*protobuf.UserBackpackResp, error) {
	var userBackpack []*protobuf.UserBackpack
	err := global.GetX().Model(&db_main3.UserBackpack{}).Raw("SELECT title,icon,animation,duration,price,type,category,gid,eff_time,quantity,exp_time,price_type,selected FROM(SELECT * "+
		"FROM(SELECT CASE WHEN (t1.type = 1 or t1.type = 2) THEN IF( eff_time <= unix_timestamp( now()) AND exp_time >= unix_timestamp( now()), 1, 0 ) ELSE 1 END filtration,t1.title,t1.icon,t1.animation,t1.duration,t1.price,"+
		"t1.type,t1.category,t1.price_type,t2.gid,t2.eff_time,t2.exp_time,t2.quantity - t2.used_quantity quantity,t2.selected FROM basic_product t1,db_user_backpack_statistics t2 "+
		"WHERE t2.uid = ? AND t1.id = t2.gid AND t1.type = t2.type AND t2.quantity - t2.used_quantity > 0 ) t3 WHERE filtration = 1) t5 ORDER BY category,title", user_id).Scan(&userBackpack).Error
	if err != nil {
		return &protobuf.UserBackpackResp{
			UserBackpack: nil,
		}, err
	}
	var cpyData []*protobuf.UserBackpack
	// 额外过滤
	for _, v := range userBackpack {
		// 如果过期时间为0 则没有过期时间
		if v.ExpTime > time.Now().Unix() || v.ExpTime == 0 {
			cpyData = append(cpyData, v)
		}
	}
	return &protobuf.UserBackpackResp{
		UserBackpack: cpyData,
		//Props:        props,
	}, nil
}

// 用户背包选用
func UserBackpackSetSelected(ptype int32, user_id int64, ids []int64, sel int32) (*protobuf.UserBackpackSetSelectedResp, error) {
	tx := global.GetX().Begin()
	if ptype == 1 {
		if len(ids) > 3 {
			return nil, errors.New("挂件同时选用的数量不能超过3个")
		}
	}
	if ptype == 2 {
		if len(ids) > 1 {
			return nil, errors.New("弹幕同时选用的数量不能超过1个")
		}
	}
	if ptype == 3 {
		if len(ids) > 1 {
			return nil, errors.New("字体同时选用的数量不能超过1个")
		}
	}

	if ptype == 2 || ptype == 3 {
		var typeIDs []int
		err := tx.Model(&db_main3.Props{}).Where("type=?", ptype).Pluck("id", &typeIDs).Error

		if err != nil {
			tx.Rollback()
			return &protobuf.UserBackpackSetSelectedResp{
				Status: 2,
			}, err
		}

		err = tx.Model(&db_main3.UserBackpack{}).Where("uid=? and gid in (?)", user_id, typeIDs).Update("selected", 0).Error
		if err != nil {
			tx.Rollback()
			return &protobuf.UserBackpackSetSelectedResp{
				Status: 2,
			}, err
		}

	}

	var selected int
	if sel == 1 {
		selected = 1
	}
	if sel == 2 {
		selected = 0
	}

	err := tx.Model(&db_main3.UserBackpack{}).Where("uid=? and id in (?)", user_id, ids).Update("selected", selected).Error
	if err != nil {
		tx.Rollback()
		return &protobuf.UserBackpackSetSelectedResp{
			Status: 2,
		}, err
	}
	err = tx.Commit().Error
	return &protobuf.UserBackpackSetSelectedResp{
		Status: 1,
	}, err
}

// 主播中心报表
func AnchorLiveStat(req *protobuf.LiveStatReq) (*protobuf.LiveStatSummaryResp, error) {
	var liveStat []*protobuf.LiveStat
	var todaySummary protobuf.TodaySummary
	var liveSummary protobuf.LiveSummary

	err := global.Live().Model(&models_live.LiveStat{}).
		Select("id, date, sum(diamond) as diamond, sum(visitor) as visitor, sum(new_fans) as new_fans, (lost_fans) as lost_fans, (total_fans) as total_fans, sum(times) as times, sum(diamond) as diamond, sum(duration) as live_duration, other_gift").
		Where("anchor_id=? and date>=? and date<=?", req.AnchorId, req.StartDate, req.EndDate).
		Group("date").
		Limit(31).
		Scan(&liveStat).Error
	if err != nil {
		return &protobuf.LiveStatSummaryResp{
			TodaySummary: nil,
			LiveSummary:  nil,
			LiveStat:     nil,
		}, err
	}

	today := time.Now().Format("2006-01-02")
	income, err := AnchorIncome(int(req.AnchorId), today)
	if err != nil {
		return &protobuf.LiveStatSummaryResp{
			TodaySummary: nil,
			LiveSummary:  nil,
			LiveStat:     nil,
		}, err
	}
	todaySummary.Diamond = int64(income.Income)
	todaySummary.OtherGift = int64(income.EagleDiamond)
	st, et := utils.OneDayRange2Unix(today)
	err = global.Live().Model(&models_live.LiveHistory{}).
		Select("count(id) as times, sum(end_stamp - start_stamp) as live_duration").
		Where("anchorid=? and end_stamp>=? and end_stamp<=?", req.AnchorId, st, et).
		Scan(&todaySummary).Error
	if err != nil {
		return &protobuf.LiveStatSummaryResp{
			TodaySummary: nil,
			LiveSummary:  nil,
			LiveStat:     nil,
		}, err
	}

	var tlh []models_live.LiveHistory

	err = global.Live().Model(&models_live.LiveHistory{}).
		Select("id, anchorid, liveid").
		Where("anchorid=? and end_stamp>=? and end_stamp<=?", req.AnchorId, st, et).
		Scan(&tlh).Error
	if err != nil {
		return &protobuf.LiveStatSummaryResp{
			TodaySummary: nil,
			LiveSummary:  nil,
			LiveStat:     nil,
		}, err
	}

	for _, v := range tlh {
		var visitor int64
		err = global.Live().Model(&models_live.LiveStreamHistory{}).Where("anchorid=? and liveid=?", v.Anchorid, v.Liveid).Count(&visitor).Error
		if err != nil {
			global.Log.Error("SyncAnchorLiveData Get Visitor Data error in: %+v", err)
		}
		todaySummary.Visitor += visitor
	}

	// 观众
	// var visitor int64
	// global.Live().Model(&models.LiveStreamHistory{}).Where("anchorid=? and last_visit_time>=? and last_visit_time<=?", req.ReceiveUid, st, et).Count(&visitor)
	// todaySummary.Visitor = visitor

	var newFans int64
	// 当日新增
	global.Live().Model(&db_main3.AnchorFans{}).Where("anchorid=? and create_time>=? and create_time<=?", req.AnchorId, today, today+" 23:59:59").Count(&newFans)
	todaySummary.NewFans = newFans

	var ls []*protobuf.LiveStat

	if req.Size > 0 {
		// 优化pc端图表显示
		loc, _ := time.LoadLocation("Local")
		startTime, _ := time.ParseInLocation("2006-01-02", req.StartDate, loc)

		for i := 0; i < int(req.Size); i++ {
			var l protobuf.LiveStat
			l.Date = startTime.Add(time.Hour * time.Duration(24*i)).Format("2006-01-02T00:00:00+08:00")
			ls = append(ls, &l)
		}

		for idx, k := range ls {
			//当前新增和总计粉丝
			// 当日新增
			queryDate, _ := time.Parse("2006-01-02T00:00:00+08:00", k.Date)
			day := queryDate.Format("2006-01-02")
			global.Live().Model(&db_main3.AnchorFans{}).Where("anchorid=? and create_time>=? and create_time<=?", req.AnchorId, day, day+" 23:59:59").Count(&k.NewFans)

			// 当前日总粉丝总数
			err = global.Live().Model(&db_main3.AnchorFans{}).
				Select("count(id) as total_fans").Where("anchorid=? and create_time<=?", req.AnchorId, day+" 23:59:59").
				Scan(&k.TotalFans).Error
			if err != nil {
				global.Log.Error("SyncAnchorLiveData Get TotalFans Data error in: %+v", err)
			}
			for _, v := range liveStat {
				if v.Date == k.Date {
					ls[idx] = v
				}
			}
		}
	} else {
		ls = liveStat
	}

	for _, v := range liveStat {
		liveSummary.Diamond += v.Diamond
		liveSummary.LiveDuration += v.LiveDuration
		liveSummary.LostFans += v.LostFans
		liveSummary.NewFans += v.NewFans
		liveSummary.OtherGift += v.OtherGift
		liveSummary.Times += v.Times
		liveSummary.Visitor += v.Visitor

	}

	return &protobuf.LiveStatSummaryResp{
		TodaySummary: &todaySummary,
		LiveSummary:  &liveSummary,
		LiveStat:     ls,
	}, nil
}

// 统计主播某日收入
func AnchorIncome(anchorId int, date string) (*db_main3.AnchorIncome, error) {

	today := time.Now().Format("2006-01-02")
	// startStr := date + " 00:00:00"
	// startTime, _ := timehelper.Parse(util.TIME_LAYOUT_FORMAT_1, startStr)
	// endTime := startTime.Add(24 * timehelper.Hour)

	dateDay, _ := time.Parse(timehelper.TIME_LAYOUT_FORMAT_4, date)
	todayDay, _ := time.Parse(timehelper.TIME_LAYOUT_FORMAT_4, today)
	if dateDay.After(todayDay) { //如果date的日期大于今天
		return nil, errors.New("err date")
	}

	//查询主播某天收入是否已经存在
	anchorIncome := &db_main3.AnchorIncome{}
	err := global.Live().Model(&anchorIncome).Where("anchorid = ? and date = ?", anchorId, date).Take(&anchorIncome).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return anchorIncome, err
	}
	if errors.Is(err, gorm.ErrRecordNotFound) { //如果不存在就在suser_profit中统计
		param := map[string]interface{}{
			"uid":          anchorId,
			"consume_type": 5,
			"create_time":  map[string]interface{}{">=": date, "<=": date + " 23:59:59"},
		}
		selectCol := "id,uid,(sum(coin_count)) as coin_count,coin_type"
		o := make([]*db_main3.UserProfit, 0) //o是以coin_type的分组查询切片
		table := global.GetR().Model(&db_main3.UserProfit{})
		table.Select(selectCol)
		mysql.Condition(table, param, "coin_type", "", 0, 0)
		err := table.Find(&o).Error
		if err != nil {
			return nil, err
		}

		for _, v := range o {
			if v.CoinType == 2 { //判断主播收益类型
				anchorIncome.Income = v.CoinCount
			} else {
				anchorIncome.EagleDiamond = v.CoinCount
			}
		}
		anchorIncome.Anchorid = anchorId
		anchorIncome.Date = timehelper.Str2Time(date)

		if date != today { //如果不是今天的收益就入库
			err := global.Live().Create(anchorIncome).Error
			if err != nil {
				return anchorIncome, err
			}
		}
	}

	return anchorIncome, nil
}

// 统计主播直播场次收益
func AnchorLiveIDIncome(anchorId int, liveId int64) (*api_models.LiveIDIncome, error) {

	param := map[string]interface{}{
		"anchorid": anchorId,
		"liveid":   liveId,
	}
	selectCol := "anchorid,liveid,(sum(anchor_profit)) as spend,spend_type"
	o := make([]*db_main3.GiftLog, 0) //o为以spend_type的分组查询
	table := global.Live().Model(&db_main3.GiftLog{})
	table.Select(selectCol)
	mysql.Condition(table, param, "spend_type", "", 0, 0)
	err := table.Find(&o).Error
	if err != nil {
		return nil, err
	}

	//主播场次收益
	income := &api_models.LiveIDIncome{}
	for _, v := range o {
		if v.SpendType == 2 {
			income.Income = v.Spend
		} else {
			income.EagleDiamond = v.Spend
		}
	}

	return income, nil
}

// 统计主播直播场次收益
func AnchorLiveIDsIncome(liveIDs []int64) []api_models.LiveIDIncome {
	var res []api_models.LiveIDIncome
	var gl []db_main3.GiftLog
	global.Live().Model(&db_main3.GiftLog{}).Select("anchorid,liveid,(sum(anchor_profit)) as spend,spend_type").
		Where("liveid", liveIDs).
		Group("spend_type, liveid").
		Scan(&gl)

	//主播场次收益
	for _, v := range gl {
		var tmp api_models.LiveIDIncome
		tmp.Liveid = v.Liveid
		tmp.SpendType = int32(v.SpendType)
		if v.SpendType == 2 {
			tmp.Income = v.Spend
		} else {
			tmp.EagleDiamond = v.Spend
		}

		res = append(res, tmp)
	}

	return res
}

func AnchorLiveIDGiftNum(liveIDs []int64) []api_models.LiveIDGiftNum {
	var res []api_models.LiveIDGiftNum
	global.Live().Model(&db_main3.GiftLog{}).Select("liveid, count(id) as gift_num").Where("liveid", liveIDs).Group("uid").Scan(&res)
	return res
}

func AnchorLiveIDVisitorNum(liveIDs []int64) []api_models.LiveIDVisitorNum {
	var res []api_models.LiveIDVisitorNum
	global.Live().Model(&models_live.LiveStreamHistory{}).Select("liveid, count(id) as visitor_num").Where("liveid", liveIDs).Group("liveid").Scan(&res)
	return res
}

/**
 * @Author admin
 * @Description //
 * @version: v1.8.0
 * @Date 16:40 2022/8/15
 * @Param
 * @return
 **/
func GetLiveSeoList() ([]*protobuf.LiveSeo, error) {
	o := make([]*protobuf.LiveSeo, 0)
	if err := global.GetR().Raw("SELECT t1.anchorid room_id,t2.nick_name,t3.title live_cat_name FROM db.db_live t1,main.db_user t2,models_live.db_live_category t3 where t2.id=t1.anchorid and t1.categoryid=t3.id").Find(&o).Error; err != nil {
		return nil, err
	}
	return o, nil
}

/**
 * @Author willi
 * @Description //TODO
 * @Date 17:52 2022/9/8
 * @Param
 * @return
 **/
func PropsSubtract(uid, gid, propsType, quantity int) int64 {
	rowsAffected := global.GetR().Exec("update db_user_backpack_statistics set used_quantity=used_quantity+? where uid=? and gid=? and type=? and quantity>=used_quantity+?", quantity, uid, gid, propsType, quantity).RowsAffected
	return rowsAffected
}

func GetIdle(ids []int) (int, error) {
	var err error

	for idx, v := range ids {
		i, err := db_main.CheckBannedlive(v)
		if err != nil {
			global.Log.Errorf("CheckBannedlive error:%v", err)
			continue
		}
		if i == 0 {
			continue
		}
		if i > 0 && time.Now().Unix() < int64(i) {
			continue
		}
		//再次确认主播是否空闲
		var check int64
		err = global.Live().Model(&models_live.Live{}).Where("anchorid=?", v).Count(&check).Error

		if err != nil && err != gorm.ErrRecordNotFound {
			continue
		}
		if check == 0 {
			return ids[idx], nil
		}
	}
	return 0, err
}

// 统计用户点击私聊情况
func LiveOpenChatNum(anchorID int, userID int) {
	var live models_live.Live
	global.Live().Model(&live).Where("anchorid=?", anchorID).First(&live)
	if live.Liveid > 0 {
		key := fmt.Sprintf("LiveOpenChatNum:%d:%d:%d", anchorID, userID, live.Liveid)
		r, _ := global.GetRds().Get(key).Result()
		if r == "" {
			// 更新统计
			global.Live().Model(&live).Where("anchorid=?", anchorID).Update("open_chat_num", gorm.Expr("open_chat_num+1"))
			global.GetRds().Set(key, 1, 3600*24*time.Second)
		}
	}
}

func LiveSendChatNum(anchorID int, userID int) {
	var live models_live.Live
	global.Live().Model(&live).Where("anchorid=?", anchorID).First(&live)
	if live.Liveid > 0 {
		key := fmt.Sprintf("LiveSendChatNum:%d:%d:%d", anchorID, userID, live.Liveid)
		r, _ := global.GetRds().Get(key).Result()
		if r == "" {
			// 更新统计
			global.Live().Model(&live).Where("anchorid=?", anchorID).Update("send_chat_num", gorm.Expr("send_chat_num+1"))
			global.GetRds().Set(key, 1, 3600*24*time.Second)
		}
	}
}
